import { Component, ViewChild, OnInit } from '@angular/core';
import { ServerDataSource } from 'ng2-smart-table';
// api
import { BasicService } from '../../../@core/data/basic.service';
// import { Observable } from 'rxjs/Rx';
import { Http } from '@angular/http';
// 消息提醒
import { ToasterConfig } from 'angular2-toaster';
import { NotificationsService } from '../../../@core/utils/notifications.service';
// confirm
import { SwalComponent } from '@toverux/ngx-sweetalert2';
const api = 'configs';
@Component({
  selector: 'ngx-smart-table-config',
  templateUrl: './config.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
  `],

})
export class ConfigComponent implements OnInit {
  @ViewChild('deleteSwal') private deleteSwal: SwalComponent;
  settings = {
    // selectMode: 'multi', //多选，全选操作未实现
    actions: {
      columnTitle: '操作',
      position: 'right',
    },
    noDataMessage: '暂无数据',
    mode: 'inline',
    pager: {
      perPage: 10,
    },
    add: {
      addButtonContent: '<i class="nb-plus"></i>',
      createButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmCreate: true,
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      // id: {
      //   title: 'ID',
      //   type: 'number',
      //   sort: 'enable',//表内排序
      //   sortDirection: 'desc'
      // },
      name: {
        title: '配置代码',
        type: 'string',
      },
      val: {
        title: '配置名称',
        type: 'string',
      },
      ctype: {
        title: '配置分类',
        type: 'string',
      },
      text: {
        title: '配置说明',
        type: 'string',
      },
      statusName: {
        title: '状态',
        type: 'string',
      },
    },
  };

  source: ServerDataSource;

  config: ToasterConfig;

  constructor(private service: BasicService, private http: Http, private notificationsService: NotificationsService) {
    this.source = new ServerDataSource(http,
      {
        endPoint: this.service.api + api,
        totalKey: this.service.totalKey,
        dataKey: this.service.dataKey,
        sortFieldKey: this.service.sortFieldKey,
        sortDirKey: this.service.sortDirKey,
        pagerPageKey: this.service.pagerPageKey,
        pagerLimitKey: this.service.pagerLimitKey,
        filterFieldKey: this.service.filterFieldKey,
      });
    this.config = this.notificationsService.getConfig();
  }

  ngOnInit() {
    // this.getAll();
    // console.log('role ngOnInit');
  }

  /**
   * 新增操作
   * @param event
   */
  onCreateConfirm(event) {
    this.create(event);
  }

  /**
   * 更新
   * @param event
   */
  onSaveConfirm(event) {
    this.update(event);
  }

  /**
   * 删除
   * @param event
   */
  onDeleteConfirm(event): void {
    this.deleteSwal.show().then(option => {
      if (option.value) {
        this.delete(event);
      }
    }).catch(err => {
      console.error(err);
      event.confirm.reject();
    });
  }

  // getAll() {
  //   this.service.getAll(api).subscribe(
  //     // the first argument is a function which runs on success
  //     data => { this.source.load(data.rows) },
  //     // the second argument is a function which runs on error
  //     err => {
  //       this.notificationsService.showToast('error', '操作', '<b>操作 <em>失败！</em></b>');
  //       console.error('Error saving!');
  //       return Observable.throw(err);
  //     }
  //   );
  // }

  create(event) {
    const newData = event.newData;
    this.service.create(api, newData).subscribe(
      data => {
        // refresh the list
        this.notificationsService.showToast('success', '操作', '<b>保存 <em>成功！</em></b>');
        event.confirm.resolve(event.newData);
        this.source.refresh();
        // return true;
      },
      err => {
        this.notificationsService.showToast('error', '操作', '<b>保存 <em>失败！</em></b>');
        console.error('Error saving!');
        event.confirm.reject();
        // return Observable.throw(err);
      },
    );
  }

  update(event) {
    const newData = event.newData;
    this.service.update(api, newData).subscribe(
      data => {
        // refresh the list
        this.notificationsService.showToast('success', '操作', '<b>更新 <em>成功！</em></b>');
        event.confirm.resolve(event.newData);
        this.source.refresh();
        // return true;
      },
      err => {
        this.notificationsService.showToast('error', '操作', '<b>更新 <em>失败！</em></b>');
        console.error('Error saving!');
        event.confirm.reject();
        // return Observable.throw(err);
      },
    );
  }

  delete(event) {
    const id = event.data.id;
    const url = api + '/' + id;
    this.service.delete(url).subscribe(
      data => {
        // refresh the list
        this.notificationsService.showToast('success', '操作', '<b>删除 <em>成功！</em></b>');
        this.source.refresh();
        // return true;
      },
      err => {
        this.notificationsService.showToast('error', '操作', '<b>删除 <em>失败！</em></b>');
        console.error('Error deleting!');
        event.confirm.reject();
        // return Observable.throw(err);
      },
    );
  }

}
